package m.system.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import m.appserver.ServerResult;
import m.appserver.ServerResultStatus;
import m.system.exception.MException;
import m.system.lang.IJsonOuter;

import java.util.LinkedHashMap;
import java.util.Map;

public class JSONMessage implements IJsonOuter, ServerResult {
	public JSONMessage(){
		jsonMap=new LinkedHashMap<>();
	}
	public JSONMessage(int code){
		jsonMap=new LinkedHashMap<>();
		jsonMap.put("code",code);
	}
	public JSONMessage(int code,String msg){
		this(code);
		jsonMap.put("msg",msg);
	}
	public JSONMessage(Map<String,Object> map){
		jsonMap=map;
	}
	private final Map<String,Object> jsonMap;
	private ServerResultStatus status=ServerResultStatus.SUCCESS;
	
	public JSONMessage push(String key,Object value){
		jsonMap.put(key, value);
		return this;
	}
	public Object get(String key){
		return jsonMap.get(key);
	}
	@SuppressWarnings("unchecked")
	public <T> T get(Class<T> clazz, String key){
		return (T)get(key);
	}
	/**
	 * 转换对象为字符串的展现形式.
	 * 
	 */
	public String toJSONString(){
		StringBuilder sb=new StringBuilder();
		for(String key : jsonMap.keySet()){
			sb.append(",\"").append(key).append("\":");
			Object value=jsonMap.get(key);
			try {
				sb.append(ObjectUtil.toString(value));
			} catch (MException e) {
				sb.append("null");
			}
		}
		return "{" + (sb.length() > 0 ? sb.substring(1) : "") + "}";
	}

	/**
	 * 转换成JSONObject
	 * @return
	 */
	public JSONObject toJSON(){
		return JSON.parseObject(toJSONString());
	}

	@Override
	public ServerResultStatus getStatus() {
		return this.status;
	}

	@Override
	public String getContent() {
		return toJSONString();
	}

	public JSONMessage setStatus(ServerResultStatus status) {
		this.status = status;
		return this;
	}

	@Override
	public String toString() {
		return this.toJSONString();
	}
	public static void main(String[] a){
		JSONMessage jj=new JSONMessage();
		jj.push("22", "22");
		JSONMessage json=new JSONMessage();
		json.push("aa", "123");
		json.push("bb", 19.2);
		json.push("cc", new Object[]{"11",new String[]{"123","124"}});
		json.push("jj", jj);
		SystemUtil.println(json.toJSONString());
	}
}
